package com.helloae.chap05;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.esri.arcgis.carto.FeatureLayer;
import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory;
import com.esri.arcgis.geodatabase.IFeatureClass;
import com.esri.arcgis.geodatabase.IFeatureWorkspace;
import com.esri.arcgis.geodatabase.IObjectClass;
import com.esri.arcgis.geodatabase.IObjectClassProxy;
import com.esri.arcgis.geodatabase.IRelationshipClass;
import com.esri.arcgis.geodatabase.ITable;
import com.esri.arcgis.geodatabase.MemoryRelationshipClassFactory;
import com.esri.arcgis.geodatabase.esriRelCardinality;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;

/**
 * 将wpdata.dbf关联(relate)到wp.shp上<br>
 * 之前所有的代码都和JoinTableToLayer一样，除了最后使用pFeatureLayer.addRelationshipClass(pRelClass);<br>
 * 示例章节：5.6.3
 * @author zhushijie
 *
 */
public class RelateTableToLayer {

	public static void main(String[] args) throws UnknownHostException, IOException {
		// 初始化AE许可
		EngineInitializer.initializeEngine();
		AoInitialize ao = new AoInitialize();
		ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
		
		//使用ShapefileWorkspaceFactory.openFromFile的方法创建一个Workspace
		ShapefileWorkspaceFactory pWF = new ShapefileWorkspaceFactory();
		String ecliseWorkspace = System.getenv("Eclipse3.6Workspace");
		IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace) pWF
				.openFromFile(ecliseWorkspace + "HelloAE" + File.separator
						+ "DataSet" + File.separator + "chap05", 0);
		//加载图层wp.shp
		IFeatureClass pFeatureClass = pFeatureWorkspace
				.openFeatureClass("wp");
		
		//打开用于relate的数据集wpdata，即表wpdata.dbf
		ITable pFromTable = pFeatureWorkspace.openTable("wpdata");
		IObjectClass originForeignClass =new IObjectClassProxy(pFromTable);

		MemoryRelationshipClassFactory pMemRelFact = new MemoryRelationshipClassFactory();
		IRelationshipClass pRelClass = pMemRelFact.open("TableRelateToLayer", pFeatureClass, "FID", originForeignClass, "OID", "hello", "hello2", esriRelCardinality.esriRelCardinalityOneToOne);
		
		FeatureLayer pFeatureLayer = new FeatureLayer();
		pFeatureLayer.setFeatureClassByRef(pFeatureClass);
		
		pFeatureLayer.addRelationshipClass(pRelClass);
		
		//这一句用来验证relate是否成功，如果放在addRelationshipClass的前面，会报错，放在后面就成功
		pFeatureLayer.removeRelationshipClass(pRelClass);
		
		ao.shutdown();
		System.out.println("Congratulations!");
	}

}
